<template>
    <view class="page-body">
        <!-- 页面内容开始 -->

        <!-- 表格搜索组件开始 -->
        <vk-data-table-query v-model="queryForm1.formData" :columns="queryForm1.columns"
            :main-columns="['detection_category', 'client', 'no', 'submitUser', 'remark']" size="mini"
            @search="search"></vk-data-table-query>
        <!-- 表格搜索组件结束 -->

        <!-- 自定义按钮区域开始 -->
        <view>
            <el-row>
                <el-button type="success" size="mini" icon="el-icon-circle-plus-outline"
                    @click="addBtn('normal')">添加(常规)</el-button>
                <el-button type="success" size="mini" icon="el-icon-circle-plus-outline"
                    @click="addBtn('aquatic')">添加(水产)</el-button>
                <el-button type="success" size="mini" icon="el-icon-circle-plus-outline"
                    @click="addBtn('enzyme')">添加(酶抑制)</el-button>
                <el-upload style="display: inline-block; margin-left: 10px" size="mini" class="upload-demo" ref="upload"
                    action="" :file-list="fileList" :auto-upload="false" :on-change="handleFileChange"
                    accept=".xlsx,.xls" :limit="1">
                    <el-button slot="trigger" size="mini" type="primary">批量导入</el-button>
                </el-upload>
                <!-- 批量操作 -->
                <el-dropdown v-if="table1.multipleSelection" :split-button="false" trigger="click" @command="batchBtn">
                    <el-button type="danger" size="mini" style="margin-left: 20rpx"
                        :disabled="table1.multipleSelection.length === 0">
                        批量操作
                        <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="1">批量打印</el-dropdown-item>
                        <el-dropdown-item :command="2"
                            v-if="$hasPermission(`detection-form-del`)">批量删除</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-row>
        </view>
        <!-- 自定义按钮区域结束 -->

        <!-- 表格组件开始 -->
        <vk-data-table ref="table1" :rowNo="true" :border="true" :action="table1.action" :columns="table1.columns"
            :query-form-param="queryForm1" size="mini" :right-btns="table1.btn" :selection="true" :pagination="true"
            @update="updateBtn" @delete="deleteBtn" @current-change="currentChange" @selection-change="selectionChange"
            :custom-right-btns="table1.customRightBtns"></vk-data-table>
        <!-- 表格组件结束 -->

        <!-- 添加或编辑的弹窗开始 -->
        <vk-data-dialog v-model="form1.props.show" :title="form1.props.title" width="1450px" mode="form"
            :close-on-click-modal="false">
            <vk-data-form v-model="form1.data" size="mini" ref="form1" :rules="form1.props.rules"
                :action="form1.props.action" :before-action="form1.props.beforeAction" :form-type="form1.props.formType"
                :columns="form1.props.columns" label-width="120px" @success="
                    form1.props.show = false;
                refresh();
                " :inline="true" :columnsNumber="2">
                <template v-slot:sample_list="{ form, keyName }">
                    <el-button type="success" size="mini" icon="el-icon-circle-plus-outline" style="margin: 10px 5px"
                        @click="insertEvent(-1)">添加样品</el-button>
                    <el-button type="warning" size="mini" icon="el-icon-check" style="margin: 10px 5px"
                        @click="batchConfirmAllSamples('normal')">一键确认所有样品</el-button>
                    <vxe-table ref="xTable" keep-source border resizable show-overflow size="small"
                        :data="orderBy(form[keyName], ['orderno', 'sampleno'], ['asc', 'asc'])"
                        :edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }"
                        :scroll-x="{ enabled: true }" style="width: 100%">
                        <vxe-table-column fixed="left" type="seq" width="80"></vxe-table-column>
                        <vxe-table-column field="sampleno" min-width="120" title="样品编号" align="left" width="200"
                            :edit-render="{ name: 'visible', autofocus: '.vxe-input--inner' }">
                            <template v-slot:edit="scope">
                                <el-input type="text" id="`input_${scope.row.rowNo}`"
                                    v-model="scope.row.sampleno"></el-input>
                                <!-- <el-input :id="`input_${scope.row.rowNo}`" v-model="scope.row.sampleno" type="text"></el-input> -->
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="samplename" width="200" title="样品名称" align="left"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <!-- <vk-data-input-select
                                  size="small"
                                  v-model="scope.row.sample_id"
                                  :filterable="true"
                                  :localdata="goodsfilters"
                                  placeholder="请选择"
                                  :props="{ value: '_id', label: 'name' }"
                                  width="180px"
                                  @change="
                                      (val, formData, column, index, option) => {
                                          (scope.row.samplename = formData.name), handelSampleChane(val, formData, scope.row);
                                      }
                                  "></vk-data-input-select> -->

                                <vk-data-input-remote-select v-model="scope.row.sample_id" :query-field="'name'"
                                    placeholder="请选择分类" action="admin/base/goods/sys/getAllList"
                                    :props="{ list: 'rows', value: '_id', label: 'name' }" width="180px"
                                    :remote-search="true" @change="(val, formData, column, index, option) => {
                                        scope.row.samplename = formData.name;
                                        handelSampleChane(val, formData, scope.row);
                                    }" :limit="200"></vk-data-input-remote-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_category" width="200" align="left"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:header>
                                <span>检测项目</span>
                                <el-button type="text" size="mini" icon="el-icon-plus"
                                    @click="batchSetNormalDetectionCategory"
                                    style="margin-left: 5px; color: #409EFF;">
                                    批量
                                </el-button>
                            </template>
                            <template v-slot:edit="scope">
                                <vk-data-input-select size="small" v-model="scope.row.detection_category"
                                    :filterable="true" :localdata="scope.row.category_list" placeholder="请选择"
                                    :props="{ value: '_id', label: 'name' }" width="180px" @change="
                                        (val, formData, column, index, option) => {
                                            handelDetection_categoryChane(val, formData, scope.row);
                                        }
                                    "></vk-data-input-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_standard" title="检测方法" align="left" width="180"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <el-input type="text" v-model="scope.row.detection_standard"></el-input>
                                <!-- <el-input v-model="scope.row.detection_standard" type="text"></el-input> -->
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_include" min-width="200" title="检测限" align="left" width="150"
                            :edit-render="{ name: 'visible' }">
                            <template v-slot:edit="scope">
                                <el-input type="text" v-model="scope.row.detection_include"></el-input>
                                <!-- <el-input v-model="scope.row.detection_include" type="text"></el-input> -->
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="result" title="测试结果" align="left" width="120"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <vk-data-input-select size="small" v-model="scope.row.result_value" :localdata="[
                                    { value: 1, label: '合格' },
                                    { value: 0, label: '不合格' }
                                ]" placeholder="请选择" width="110px" @change="
                                    (val, formData, column, index, option) => {
                                        if (scope.row.result_value == 1) {
                                            scope.row.result = `阴性`;
                                            scope.row.yxresult = '阴性';
                                        } else {
                                            scope.row.result = `阳性`;
                                            scope.row.yxresult = `阳性`;
                                        }
                                    }
                                "></vk-data-input-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="remark" title="备注" align="left" width="150"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <el-input type="text" placeholder="请输入备注" v-model="scope.row.remark" maxlength="8"
                                    show-word-limit></el-input>
                            </template>
                        </vxe-table-column>

                        <vxe-column title="操作" width="150" fixed="right">
                            <template #default="{ row }">
                                <template>
                                    <el-button type="success" v-if="row.isSave == undefined || row.isSave != 1"
                                        @click="marksur(row)">确定</el-button>
                                    <el-button type="danger" @click="removeEvent(row)">删除</el-button>
                                </template>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </template>
            </vk-data-form>
        </vk-data-dialog>
        <!-- 添加或编辑的弹窗结束 -->
        <!-- 添加或编辑的弹窗开始 -->
        <vk-data-dialog v-model="form2.props.show" :title="form2.props.title" width="1250px" mode="form"
            :close-on-click-modal="false">
            <vk-data-form v-model="form2.data" size="mini" ref="form2" :rules="form2.props.rules"
                :action="form2.props.action" :before-action="form2.props.beforeAction" :form-type="form2.props.formType"
                :columns="form2.props.columns" label-width="120px" @success="
                    form2.props.show = false;
                refresh();
                " :inline="true" :columnsNumber="3"></vk-data-form>
        </vk-data-dialog>
        <!-- 添加或编辑的弹窗结束 -->

        <vk-data-dialog v-model="aquatic_form.props.show" :title="aquatic_form.props.title" width="1350px" mode="form"
            :close-on-click-modal="false">
            <vk-data-form v-model="aquatic_form.data" size="mini" ref="form1" :rules="aquatic_form.props.rules"
                :action="aquatic_form.props.action" :before-action="aquatic_form.props.beforeAction"
                :form-type="aquatic_form.props.formType" :columns="aquatic_form.props.columns" label-width="120px"
                @success="
                    aquatic_form.props.show = false;
                refresh();
                " :inline="true" :columnsNumber="2">
                <template v-slot:sample_list="{ form, keyName }">
                    <el-button type="success" size="mini" :disabled="!$fn.isNotNull(aquatic_form.data.samplename)"
                        icon="el-icon-circle-plus-outline" style="margin: 10px 5px"
                        @click="insertAquaticEvent(-1)">添加检测项目</el-button>
                    <el-button type="warning" size="mini" icon="el-icon-check" style="margin: 10px 5px"
                        @click="batchConfirmAllSamples('aquatic')">一键确认所有样品</el-button>
                    <vxe-table ref="xAQTable" keep-source border resizable show-overflow size="small"
                        :data="form[keyName]"
                        :edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }">
                        <vxe-table-column fixed="left" type="seq" width="80"></vxe-table-column>
                        <vxe-table-column field="detection_category" width="200" align="left"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:header>
                                <span>检测项目</span>
                                <el-button type="text" size="mini" icon="el-icon-plus"
                                    @click="batchSetAquaticDetectionCategory"
                                    style="margin-left: 5px; color: #409EFF;">
                                    批量
                                </el-button>
                            </template>
                            <template v-slot:edit="scope">
                                <el-select
                                    size="small"
                                    v-model="scope.row.detection_category"
                                    filterable
                                    placeholder="请选择"
                                    style="width: 180px"
                                    @change="(val) => {
                                        const option = aquatic_form.data.detection_category_list.find(item => item._id === val);
                                        handel_AQ_detection_categoryChange(val, option, scope.row);
                                    }"
                                >
                                    <el-option
                                        v-for="item in aquatic_form.data.detection_category_list"
                                        :key="item._id"
                                        :label="item.name"
                                        :value="item._id"
                                    >
                                        <div style="display: flex; justify-content: space-between; width: 100%">
                                            <span>{{ item.name }}</span>
                                            <span style="color: #909399; font-size: 12px">{{ item.detection_include || '' }}</span>
                                        </div>
                                    </el-option>
                                </el-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_standard" title="检测方法" align="left" width="180"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <el-input v-model="scope.row.detection_standard" type="text"></el-input>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="standardRequir" min-width="200" title="标准要求" align="left" width="150"
                            :edit-render="{ name: 'visible' }">
                            <template v-slot:edit="scope">
                                <el-input v-model="scope.row.standardRequir" type="text"></el-input>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_include" min-width="200" title="检测限" align="left" width="150"
                            :edit-render="{ name: 'visible' }">
                            <template v-slot:edit="scope">
                                <el-input v-model="scope.row.detection_include" type="text"></el-input>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="result" title="测试结果" align="left" width="120"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <vk-data-input-select size="small" v-model="scope.row.result_value" :localdata="[
                                    { value: 1, label: '合格' },
                                    { value: 0, label: '不合格' }
                                ]" placeholder="请选择" width="110px" @change="
                                    (val, formData, column, index, option) => {
                                        if (scope.row.result_value == 1) {
                                            scope.row.result = `阴性`;
                                            scope.row.yxresult = '阴性';
                                        } else {
                                            scope.row.result = `阳性`;
                                            scope.row.yxresult = `阳性`;
                                        }
                                    }
                                "></vk-data-input-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="remark" title="备注" align="left" width="150"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <el-input type="text" placeholder="请输入备注" v-model="scope.row.remark" maxlength="8"
                                    show-word-limit></el-input>
                                <!-- <el-input v-model="scope.row.remark" type="text"></el-input> -->
                            </template>
                        </vxe-table-column>
                        <vxe-column title="操作" width="150">
                            <template #default="{ row }">
                                <template>
                                    <el-button type="success" v-if="row.isSave == undefined || row.isSave != 1"
                                        @click="mark_aquatic_sur(row)">确定</el-button>
                                    <el-button type="danger" @click="removeAquaticEvent(row)">删除</el-button>
                                </template>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </template>
            </vk-data-form>
        </vk-data-dialog>

        <!-- 酶抑制表单 - 修改为与常规表单相似的结构 -->
        <vk-data-dialog v-model="enzyme_form.props.show" :title="enzyme_form.props.title" width="1350px" mode="form"
            :close-on-click-modal="false">
            <vk-data-form v-model="enzyme_form.data" size="mini" ref="enzymeForm" :rules="enzyme_form.props.rules"
                :action="enzyme_form.props.action" :before-action="enzyme_form.props.beforeAction"
                :form-type="enzyme_form.props.formType" :columns="enzyme_form.props.columns" label-width="120px"
                @success="
                    enzyme_form.props.show = false;
                refresh();
                " :inline="true" :columnsNumber="2">
                <template v-slot:sample_list="{ form, keyName }">
                    <el-button type="success" size="mini" icon="el-icon-circle-plus-outline" style="margin: 10px 5px"
                        @click="insertEnzymeEvent(-1)">添加样品</el-button>
                    <el-button type="primary" size="mini" icon="el-icon-plus" style="margin: 10px 5px"
                        @click="batchAddEnzymeSamples">批量添加</el-button>
                    <el-button type="warning" size="mini" icon="el-icon-check" style="margin: 10px 5px"
                        @click="batchConfirmAllSamples('enzyme')">一键确认所有样品</el-button>
                    <vxe-table ref="xEnzymeTable" keep-source border resizable show-overflow size="small"
                        :data="orderBy(form[keyName], ['orderno', 'sampleno'], ['asc', 'asc'])"
                        :edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }">
                        <vxe-table-column fixed="left" type="seq" width="80"></vxe-table-column>
                        <vxe-table-column field="sampleno" min-width="120" title="样品编号" align="left" width="180"
                            :edit-render="{ name: 'visible', autofocus: '.vxe-input--inner' }">
                            <template v-slot:edit="scope">
                                <el-input :id="`input_${scope.row.rowNo}`" v-model="scope.row.sampleno"
                                    type="text"></el-input>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="samplename" width="200" align="left"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:header>
                                <span>样品名称</span>
                                <el-button type="text" size="mini" icon="el-icon-plus"
                                    @click="batchInputSampleNames"
                                    style="margin-left: 5px; color: #409EFF;">
                                    批量
                                </el-button>
                            </template>
                            <template v-slot:edit="scope">
                                <!-- <vk-data-input-select
                                  size="small"
                                  v-model="scope.row.sample_id"
                                  :filterable="true"
                                  :localdata="goodsfilters"
                                  placeholder="请选择"
                                  :props="{ value: '_id', label: 'name' }"
                                  width="180px"
                                  @change="
                                      (val, formData, column, index, option) => {
                                          (scope.row.samplename = formData.name), handelSampleChane(val, formData, scope.row);
                                      }
                                  "></vk-data-input-select> -->

                                <vk-data-input-remote-select v-model="scope.row.sample_id" :query-field="'name'"
                                    placeholder="请选择分类" action="admin/base/goods/sys/getAllList"
                                    :props="{ list: 'rows', value: '_id', label: 'name' }" width="190px"
                                    :remote-search="true" @change="(val, formData, column, index, option) => {
                                        scope.row.samplename = formData.name;
                                        handelSampleChane(val, formData, scope.row);
                                    }" :limit="200"></vk-data-input-remote-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_category" width="200" align="left"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:header>
                                <span>检测项目</span>
                                <el-button type="text" size="mini" icon="el-icon-plus"
                                    @click="batchSetDetectionCategory"
                                    style="margin-left: 5px; color: #409EFF;">
                                    批量
                                </el-button>
                            </template>
                            <template v-slot:edit="scope">
                                <vk-data-input-select size="small" v-model="scope.row.detection_category"
                                    :filterable="true" :localdata="scope.row.category_list" placeholder="请选择"
                                    :props="{ value: '_id', label: 'name' }" width="180px" @change="
                                        (val, formData, column, index, option) => {
                                            handelEnzymeDetectionChange(val, formData, scope.row);
                                        }
                                    "></vk-data-input-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="detection_standard" title="检测方法" align="left" width="150"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <el-input v-model="scope.row.detection_standard" type="text"></el-input>
                            </template>
                        </vxe-table-column>

                        <vxe-table-column field="inhibition_rate" align="left" width="120"
                            :edit-render="{ name: 'visible' }">
                            <template v-slot:header>
                                <span>抑制率 (%)</span>
                                <el-button type="text" size="mini" icon="el-icon-plus"
                                    @click="batchInputInhibitionRates"
                                    style="margin-left: 5px; color: #409EFF;">
                                    批量
                                </el-button>
                            </template>
                            <template v-slot:edit="scope">
                                <el-input v-model="scope.row.inhibition_rate" type="text"></el-input>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="conclusion" title="判定结论" align="left" width="120"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <vk-data-input-select size="small" v-model="scope.row.result_value" :localdata="[
                                    { value: 1, label: '阴性' },
                                    { value: 0, label: '阳性' }
                                ]" placeholder="请选择" width="110px" @change="
                                    (val, formData, column, index, option) => {
                                        if (scope.row.result_value == 1) {
                                            scope.row.result = `阴性`;
                                            scope.row.yxresult = '阴性';
                                            scope.row.conclusion = '阴性';
                                            // 阴性时抑制率通常较低
                                            if (!scope.row.inhibition_rate) {
                                                scope.row.inhibition_rate = Math.floor(Math.random() * 30) + 10;
                                            }
                                        } else {
                                            scope.row.result = `阳性`;
                                            scope.row.yxresult = '阳性';
                                            scope.row.conclusion = '阳性';
                                            // 阳性时抑制率通常较高
                                            if (!scope.row.inhibition_rate) {
                                                scope.row.inhibition_rate = Math.floor(Math.random() * 30) + 50;
                                            }
                                        }
                                    }
                                "></vk-data-input-select>
                            </template>
                        </vxe-table-column>
                        <vxe-table-column field="remark" title="备注" align="left" width="120"
                            :edit-render="{ name: 'visible', autoselect: true }">
                            <template v-slot:edit="scope">
                                <el-input type="text" placeholder="请输入备注" v-model="scope.row.remark" maxlength="8"
                                    show-word-limit></el-input>
                            </template>
                        </vxe-table-column>
                        <vxe-column title="操作" width="150">
                            <template #default="{ row }">
                                <template>
                                    <el-button type="success" v-if="row.isSave == undefined || row.isSave != 1"
                                        @click="mark_enzyme_sur(row)">确定</el-button>
                                    <el-button type="danger" @click="removeEnzymeEvent(row)">删除</el-button>
                                </template>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </template>
            </vk-data-form>
        </vk-data-dialog>

        <!-- <aquaticform :Form="aquatic_form"></aquaticform> -->
        <print v-model="print" />
        <aquaticPrint v-model="print_aquatic" />
        <enzymeInhibitionPrint v-model="print_enzyme" />
        <!-- 页面内容结束 -->
    </view>
</template>

<script>
import XLSX from 'xlsx';
import print from './printbyPrintjs';
import aquaticPrint from './aquaticPrint';
import aquaticform from './components/aquatic-form';
import pinyin from 'js-pinyin';
import { remove, concat, uniqBy, find, includes, orderBy } from 'lodash';
import enzymeInhibitionPrint from './enzymeInhibitionPrint';

var that; // 当前页面对象
var vk = uni.vk; // vk实例
var originalForms = {}; // 表单初始化数据

export default {
    components: {
        print,
        aquaticform,
        aquaticPrint,
        enzymeInhibitionPrint
    },
    data() {
        // 页面数据变量
        return {
            // 页面是否请求中或加载中
            loading: false,
            fileList: [],
            detection_categorys: [], //检测项目
            detection_category_list: {},
            goods: [], //商品
            clients: [], //委托
            // 批量设置检测项目时的选中值
            selectedDetectionCategory: '',
            selectedAquaticDetectionCategory: '',
            selectedEnzymeDetectionCategory: '',
            print: {
                show: false,
                printData: []
            },
            print_aquatic: {
                show: false,
                printData: []
            },
            print_enzyme: {
                show: false,
                printData: []
            },
            // init请求返回的数据
            data: {},
            // 表格相关开始 -----------------------------------------------------------
            table1: {
                // 表格数据请求地址
                action: 'admin/testing/detection-form/sys/getList',
                // 表格字段显示规则
                columns: [
                    // { key:"_id", title:"id", type:"text", width:220 },

                    { key: 'no', title: '检测编号', type: 'text', width: 150, sortable: 'custom' },
                    { key: 'client_name', title: '委托单位/人', type: 'text', width: 200, sortable: 'custom' },
                    {
                        key: 'type',
                        title: '类别',
                        type: 'html',
                        width: 100,
                        sortable: 'custom',
                        formatter: (val, row, column, index) => {
                            let str = ``;
                            if (that.$fn.isNotNull(val)) {
                                if (val == 'aquatic') {
                                    str = `<text style="background:#409EFF;padding:10px;color:#fff">水产</text>`;
                                } else if (val == 'enzyme') {
                                    str = `<text style="background:#E6A23C;padding:10px;color:#fff">酶抑制</text>`;
                                } else {
                                    str = `<text>常规</text>`;
                                }
                            } else {
                                str = `<text>常规</text>`;
                            }
                            return str;
                        }
                    },
                    { key: 'detection_type', title: '送检类别', type: 'text', width: 100, sortable: 'custom' },
                    { key: 'submitUser', title: '抽/送样者', type: 'text', width: 150, sortable: 'custom' },
                    { key: 'detection_user', title: '检测人', type: 'text', width: 100, sortable: 'custom' },
                    { key: 'printcount', title: '打印次数', type: 'text', width: 60, sortable: 'custom' },
                    { key: 'sample_list.length', title: '样品个数', type: 'text', width: 60, sortable: 'custom' },
                    { key: 'detect_time', title: '填单时间', type: 'time', valueFormat: 'yyyy年MM月dd日', width: 150, sortable: 'custom' }
                    // { key:"_add_time", title:"添加时间", type:"time", width:160, sortable:"custom"  },
                    // { key:"_add_time", title:"距离现在", type:"dateDiff", width:120 },
                ],
                // 多选框选中的值
                multipleSelection: [],
                // 当前高亮的记录
                selectItem: '',
                btn: [],
                customRightBtns: [
                    {
                        title: '打印',
                        type: 'success',
                        icon: 'el-icon-plus',
                        show: item => {
                            return that.isDateBeforeOrEqualToToday(item.detect_time);
                        },
                        onClick: item => {
                            if (that.$fn.isNotNull(item.type) && item.type == 'aquatic') {
                                that.print_aquatic.printData = [];
                                that.print_aquatic.show = true;
                                that.print_aquatic.printData.push(vk.pubfn.deepClone(item));
                            } else if (that.$fn.isNotNull(item.type) && item.type == 'enzyme') {
                                that.print_enzyme.printData = [];
                                that.print_enzyme.show = true;
                                that.print_enzyme.printData.push(vk.pubfn.deepClone(item));
                            } else {
                                that.print.printData = [];
                                that.print.show = true;
                                that.print.printData.push(vk.pubfn.deepClone(item));
                            }
                        }
                    },
                    {
                        title: '填单时间',
                        show: item => {
                            return this.$hasRole('admin') || this.$hasPermission('detection-form-edittime');
                        },
                        onClick: item => {
                            that.form2.props.action = 'admin/testing/detection-form/sys/update';
                            that.form2.props.formType = 'update';
                            that.form2.props.title = '填单时间管理';
                            that.form2.props.show = true;
                            that.form2.data = item;
                        }
                    }
                ]
            },
            // 表格相关结束 -----------------------------------------------------------
            // 表单相关开始 -----------------------------------------------------------
            // 查询表单请求数据
            queryForm1: {
                // 查询表单数据源，可在此设置默认值
                formData: {},
                // 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
                columns: [
                    // { key: "client", title: "委托单位/人", type: "text", width: 160, mode: "%%" },
                    {
                        key: 'detection_category',
                        title: '检测项目',
                        type: 'remote-select',
                        placeholder: '请选择分类',
                        action: 'admin/base/detection_category/sys/getList',
                        props: { list: 'rows', value: '_id', label: 'name' },
                        showAll: true,
                        actionData: {
                            pageSize: 1000
                        },
                        width: 150
                    },
                    {
                        key: 'client',
                        title: '委托单位/人',
                        type: 'select',
                        placeholder: '请选择分类',
                        filterable: true,
                        data: [],
                        props: { list: 'rows', value: '_id', label: 'name' },
                        width: 150
                    },

                    { key: 'no', title: '编号', type: 'text', width: 160, mode: '%%' },
                    { key: 'submitUser', title: '抽/送样者', type: 'text', width: 160, mode: '%%' },
                    {
                        key: 'remark',
                        title: '备注',
                        type: 'text',
                        width: 160,
                        mode: '%%',
                        fieldName: 'sample_list.remark',
                        lastWhereJson: true
                    },
                    { key: 'detect_time', title: '填单时间', type: 'datetimerange', width: 380, mode: '[]' }
                ]
            },
            form1: {
                // 表单请求数据，此处可以设置默认值
                data: {
                    detection_user: vk.getVuex('$user.userInfo').nickname,
                    detection_type: '委托检测'
                },
                // 表单属性
                props: {
                    // 表单请求地址
                    action: '',
                    beforeAction: _formData => {
                        let formData = JSON.parse(JSON.stringify(_formData));
                        const $table = this.$refs.xTable;
                        const { insertRecords, removeRecords, updateRecords } = $table.getRecordset();
                        if (that.$fn.isNull(formData.sample_list)) {
                            formData.sample_list = [];
                        }
                        console.log(formData.sample_list);
                        if (that.$fn.isNull(formData.detect_time)) {
                            formData.detect_time = new Date().getTime();
                        }
                        if (formData.sample_list.length > 0) {
                            formData.sample_list = uniqBy(concat(formData.sample_list, insertRecords), `_X_ROW_KEY`);
                        } else formData.sample_list = insertRecords;

                        removeRecords.forEach(element => {
                            let _del = find(formData.sample_list, x => {
                                if (that.$fn.isNull(x.rowNo)) {
                                    return x._X_ROW_KEY == element._X_ROW_KEY;
                                } else return x.rowNo == element.rowNo;
                            });
                            that.$set(_del, 'isdel', true);
                        });

                        if (that.$fn.isNull(formData.sample_list.filter(x => that.$fn.isNull(x.isdel) || !x.isdel))) {
                            vk.alert(`至少包含一条样品检测数据`);
                            return false;
                        }

                        try {
                            let i = 1;
                            formData.sample_list.forEach(element => {
                                if (that.$fn.isNull(element.isSave) || element.isSave == 0) {
                                    throw new Error(`第${i}行数据未确认`);
                                }
                                i++;
                            });
                        } catch (e) {
                            vk.alert(e.message);
                            return false;
                        }
                        // 可在此处修改 formData 后返回 formData，若在此处return false，则表单不触发提交请求。

                        return formData;
                    },
                    // 表单字段显示规则
                    columns: [
                        {
                            key: 'client',
                            title: '委托单位/人',
                            type: 'remote-select',
                            placeholder: '请选择委托单位/人',
                            filterable: true,
                            action: 'admin/base/client/sys/getalllist',
                            props: { list: 'rows', value: '_id', label: 'name' },

                            showAll: true,
                            actionData: {
                                pageSize: -1
                            },
                            watch: ({ value, formData, column, index, option, $set }) => {
                                $set('submitUser', option.name);
                                $set('client_name', option.name);
                                $set('address', option.address);
                                if (that.$fn.isNull(option.addressps)) {
                                    $set('submituser_address', option.address);
                                } else
                                    $set('submituser_address', option.addressps);
                            },
                            width: 300
                        },
                        {
                            key: 'detection_type',
                            title: '检测类别',
                            type: 'select',
                            filterable: true,
                            clearable: true,
                            data: [
                                { value: '委托检测', label: '委托检测' },
                                { value: '抽检', label: '抽检' },
                                { value: '驻点抽检', label: '驻点抽检' }
                            ],
                            width: 300
                        },
                        { key: 'address', title: '委托单位地址', type: 'text', width: 300, sortable: 'custom' },
                        {
                            key: 'submitUser', title: '抽/送样者', type: 'text', width: 300, sortable: 'custom',
                            watch: ({ value, formData, column, index, option, $set }) => {
                                //   $set('submitUser', option.name);
                                //   $set('client_name', option.name);
                                //   $set('address', option.address);
                                //   $set('submituser_address', option.addressps);
                            },
                        },
                        { key: 'submituser_address', title: '抽/送样者地址', type: 'text', width: 300, sortable: 'custom' },
                        { key: 'detection_user', title: '检测人', type: 'text', width: 300, sortable: 'custom', disabled: true },
                        { key: 'remark', title: '备注', type: 'text', width: 800, oneLine: true, sortable: 'custom' },
                        { key: 'sample_list', title: '', type: 'text', width: 800 }
                    ],
                    // 表单验证规则
                    rules: {
                        client: [
                            // 必填
                            { required: true, message: '委托单位/人不能为空', trigger: 'change' }
                        ],
                        detection_type: [
                            // 必填
                            { required: true, message: '检测类别', trigger: 'change' }
                        ],
                        submitUser: [
                            // 必填
                            { required: true, message: '抽/送样者', trigger: 'change' }
                        ],

                        detection_user: [
                            // 必填
                            { required: true, message: '检测人', trigger: 'change' }
                        ]
                    },
                    // add 代表添加 update 代表修改
                    formType: '',
                    // 是否显示表单的弹窗
                    show: false
                }
            },
            aquatic_form: {
                // 表单请求数据，此处可以设置默认值
                data: {
                    detection_user: vk.getVuex('$user.userInfo').nickname,
                    detection_type: '委托检测'
                },
                // 表单属性
                props: {
                    // 表单请求地址
                    action: '',
                    beforeAction: _formData => {
                        const $table = this.$refs.xAQTable;
                        let formData = JSON.parse(JSON.stringify(_formData));
                        const { insertRecords, removeRecords, updateRecords } = $table.getRecordset();
                        if (that.$fn.isNull(formData.sample_list)) {
                            formData.sample_list = [];
                        }

                        if (that.$fn.isNull(formData.detect_time)) {
                            formData.detect_time = new Date().getTime();
                        }
                        if (formData.sample_list.length > 0) {
                            formData.sample_list = uniqBy(concat(formData.sample_list, insertRecords, updateRecords), `_X_ROW_KEY`);
                        } else formData.sample_list = insertRecords;
                        removeRecords.forEach(element => {
                            let _del = find(formData.sample_list, x => {
                                if (that.$fn.isNull(x.rowNo)) {
                                    return x._X_ROW_KEY == element._X_ROW_KEY;
                                } else return x.rowNo == element.rowNo;
                            });
                            that.$set(_del, 'isdel', true);
                        });

                        try {
                            let i = 1;
                            formData.sample_list.forEach(element => {
                                if (that.$fn.isNull(element.isSave) || element.isSave == 0) {
                                    throw new Error(`第${i}行数据未确认`);
                                }
                                i++;
                            });
                        } catch (e) {
                            vk.alert(e.message);
                            return false;
                        }
                        formData.sample_list.map(x => {
                            that.$set(x, 'sampleno', formData.sampleno);
                            that.$set(x, 'samplename', formData.samplename);
                            that.$set(x, 'sample_id', formData.sample_id);
                        });
                        if (that.$fn.isNull(formData.sample_list.filter(x => that.$fn.isNull(x.isdel) || !x.isdel))) {
                            vk.alert(`至少包含一条样品检测数据`);
                            return false;
                        }

                        console.log(formData);

                        return formData;
                    },
                    // 表单字段显示规则
                    columns: [
                        {
                            key: 'client',
                            title: '委托单位/人',
                            type: 'remote-select',
                            placeholder: '请选择委托单位/人',
                            filterable: true,
                            action: 'admin/base/client/sys/getalllist',
                            props: { list: 'rows', value: '_id', label: 'name' },

                            showAll: true,
                            actionData: {
                                pageSize: -1
                            },
                            watch: ({ value, formData, column, index, option, $set }) => {
                                $set('submitUser', option.name);
                                $set('client_name', option.name);
                                $set('address', option.address);
                                if (that.$fn.isNull(option.addressps)) {
                                    $set('addressps', option.address);
                                } else
                                    $set('addressps', option.addressps);

                            },
                            width: 300
                        },
                        {
                            key: 'detection_type',
                            title: '检测类别',
                            type: 'select',
                            filterable: true,
                            clearable: true,
                            data: [
                                { value: '委托检测', label: '委托检测' },
                                { value: '抽检', label: '抽检' },
                                { value: '驻点抽检', label: '驻点抽检' }
                            ],
                            width: 300
                        },
                        { key: 'sampleno', title: '样品编号', type: 'text', width: 300, sortable: 'custom' },
                        {
                            key: 'samplename',
                            title: '样品名称',
                            type: 'select',
                            filterable: true,
                            props: { list: 'rows', value: '_id', label: 'name' },
                            placeholder: '请选择样品',

                            watch: ({ value, formData, column, index, option, $set }) => {
                                console.log(option, 'option');

                                let _arry = this.detection_categorys.filter(x => option.detection_category.includes(x._id));
                                $set('detection_category_list', _arry);
                                $set('sample_id', option._id);
                                $set('samplename', option.name);
                            },
                            data: [],
                            width: 300
                        },
                        { key: 'address', title: '委托单位地址', type: 'text', width: 300, sortable: 'custom' },
                        { key: 'submitUser', title: '抽/送样者', type: 'text', width: 300, sortable: 'custom' },
                        { key: 'addressps', title: '抽/送样者地址', type: 'text', width: 300, sortable: 'custom' },
                        //   { key: 'contact', title: '联系人', type: 'text', width: 300, sortable: 'custom' },
                        //   { key: 'contact_number', title: '联系方式', type: 'text', width: 300, sortable: 'custom' },
                        // { key: "sale_for", title: "销售流向", type: "text", width: 300, sortable: "custom" },


                        { key: 'detection_user', title: '检测人', type: 'text', width: 300, sortable: 'custom', disabled: true },
                        { key: 'remark', title: '备注', type: 'text', width: 800, sortable: 'custom', oneLine: true },
                        { key: 'sample_list', title: '', type: 'text', width: 800, oneLine: true }
                    ],
                    // 表单验证规则
                    rules: {
                        client: [
                            // 必填
                            { required: true, message: '委托单位/人不能为空', trigger: 'change' }
                        ],
                        detection_type: [
                            // 必填
                            { required: true, message: '检测类别能为空', trigger: 'change' }
                        ],
                        submitUser: [
                            // 必填
                            { required: true, message: '抽/送样者能为空', trigger: 'change' }
                        ],

                        detection_user: [
                            // 必填
                            { required: true, message: '检测人能为空', trigger: 'change' }
                        ],
                        sampleno: [
                            // 必填
                            { required: true, message: '样品编号能为空', trigger: 'change' }
                        ],
                        samplename: [
                            // 必填
                            { required: true, message: '样品名称能为空', trigger: 'change' }
                        ]
                    },
                    // add 代表添加 update 代表修改
                    formType: '',
                    // 是否显示表单的弹窗
                    show: false
                }
            },
            // 新增酶抑制表单 - 结构类似常规表单
            enzyme_form: {
                // 表单请求数据，此处可以设置默认值
                data: {
                    detection_user: vk.getVuex('$user.userInfo').nickname,
                    type: 'enzyme',
                    detection_type: '委托检测'
                },
                // 表单属性
                props: {
                    // 表单请求地址
                    action: '',
                    beforeAction: _formData => {
                        const $table = this.$refs.xEnzymeTable;
                        let formData = JSON.parse(JSON.stringify(_formData));
                        const { insertRecords, removeRecords, updateRecords } = $table.getRecordset();
                        if (that.$fn.isNull(formData.sample_list)) {
                            formData.sample_list = [];
                        }

                        if (that.$fn.isNull(formData.detect_time)) {
                            formData.detect_time = new Date().getTime();
                        }
                        if (formData.sample_list.length > 0) {
                            formData.sample_list = uniqBy(concat(formData.sample_list, insertRecords), `_X_ROW_KEY`);
                        } else formData.sample_list = insertRecords;
                        removeRecords.forEach(element => {
                            let _del = find(formData.sample_list, x => {
                                if (that.$fn.isNull(x.rowNo)) {
                                    return x._X_ROW_KEY == element._X_ROW_KEY;
                                } else return x.rowNo == element.rowNo;
                            });
                            that.$set(_del, 'isdel', true);
                        });

                        if (that.$fn.isNull(formData.sample_list.filter(x => that.$fn.isNull(x.isdel) || !x.isdel))) {
                            vk.alert(`至少包含一条样品检测数据`);
                            return false;
                        }

                        try {
                            let i = 1;
                            formData.sample_list.forEach(element => {
                                if (that.$fn.isNull(element.isSave) || element.isSave == 0) {
                                    throw new Error(`第${i}行数据未确认`);
                                }
                                // 验证抑制率是否已填写
                                if (that.$fn.isNull(element.inhibition_rate)) {
                                    throw new Error(`第${i}行抑制率不能为空`);
                                }
                                i++;
                            });
                        } catch (e) {
                            vk.alert(e.message);
                            return false;
                        }

                        return formData;
                    },
                    // 表单字段显示规则
                    columns: [
                        {
                            key: 'client',
                            title: '委托单位/人',
                            type: 'remote-select',
                            placeholder: '请选择委托单位/人',
                            filterable: true,
                            action: 'admin/base/client/sys/getalllist',
                            props: { list: 'rows', value: '_id', label: 'name' },

                            showAll: true,
                            actionData: {
                                pageSize: -1
                            },
                            watch: ({ value, formData, column, index, option, $set }) => {
                                $set('submitUser', option.name);
                                $set('client_name', option.name);
                                $set('address', option.address);
                                if (that.$fn.isNull(option.addressps)) {
                                    $set('submituser_address', option.address);
                                } else
                                    $set('submituser_address', option.addressps);
                            },
                            width: 300
                        },
                        {
                            key: 'detection_type',
                            title: '检测类别',
                            type: 'select',
                            filterable: true,
                            clearable: true,
                            data: [
                                { value: '委托检测', label: '委托检测' },
                                { value: '抽检', label: '抽检' },
                                { value: '驻点抽检', label: '驻点抽检' }
                            ],
                            width: 300
                        },
                        { key: 'address', title: '委托单位地址', type: 'text', width: 300, sortable: 'custom' },
                        { key: 'submitUser', title: '抽/送样者', type: 'text', width: 300, sortable: 'custom' },
                        { key: 'submituser_address', title: '抽/送样者地址', type: 'text', width: 300, sortable: 'custom' },
                        { key: 'detection_user', title: '检测人', type: 'text', width: 300, sortable: 'custom', disabled: true },
                        { key: 'remark', title: '备注', type: 'text', width: 800, oneLine: true, sortable: 'custom' },
                        { key: 'sample_list', title: '', type: 'text', width: 800 }
                    ],
                    // 表单验证规则
                    rules: {
                        client: [
                            { required: true, message: '委托单位/人不能为空', trigger: 'change' }
                        ],
                        detection_type: [
                            { required: true, message: '检测类别不能为空', trigger: 'change' }
                        ],
                        submitUser: [
                            { required: true, message: '抽/送样者不能为空', trigger: 'change' }
                        ],
                        detection_user: [
                            { required: true, message: '检测人不能为空', trigger: 'change' }
                        ]
                    },
                    // add 代表添加 update 代表修改
                    formType: '',
                    // 是否显示表单的弹窗
                    show: false,
                    title: '酶抑制检测表单'
                }
            },
            form2: {
                // 表单请求数据，此处可以设置默认值
                data: {},
                // 表单属性
                props: {
                    // 表单请求地址
                    action: '',

                    // 表单字段显示规则
                    columns: [
                        {
                            key: 'client_name',
                            title: '委托单位/人',
                            type: 'text',
                            placeholder: '请选择委托单位/人',
                            disabled: true,
                            props: { list: 'rows', value: '_id', label: 'name' },
                            data: [],

                            width: 200
                        },
                        {
                            key: 'detection_type',
                            title: '检测类别',
                            type: 'select',
                            filterable: true,
                            clearable: true,
                            data: [
                                { value: '送检', label: '送检' },
                                { value: '抽检', label: '抽检' },
                                { value: '驻点抽检', label: '驻点抽检' }
                            ],
                            disabled: true,
                            width: 200
                        },

                        { key: 'submitUser', title: '抽/送样者', type: 'text', width: 200, sortable: 'custom', disabled: true },
                        { key: 'detection_user', title: '检测人', disabled: true, type: 'text', width: 200, sortable: 'custom' },
                        {
                            key: 'detect_time',
                            title: '填单时间',
                            type: 'date',
                            dateType: 'date',
                            width: 200,
                            sortable: 'custom',
                            watch: ({ value, formData, column, index, option, $set }) => {
                                // 当填单日期变更时，提示用户编号将重新生成
                                if (that.queryForm1.formType === 'update' && value) {
                                    that.$message.info('填单日期已变更，保存时将重新生成检测单编号');
                                }
                            }
                        },

                    ],
                    // 表单验证规则
                    rules: {
                        client: [
                            // 必填
                            { required: true, message: '委托单位/人不能为空', trigger: 'change' }
                        ],
                        detection_type: [
                            // 必填
                            { required: true, message: '检测类别', trigger: 'change' }
                        ],
                        submitUser: [
                            // 必填
                            { required: true, message: '抽/送样者', trigger: 'change' }
                        ],
                        detection_user: [
                            // 必填
                            { required: true, message: '检测人', trigger: 'change' }
                        ]
                    },
                    // add 代表添加 update 代表修改
                    formType: '',
                    // 是否显示表单的弹窗
                    show: false
                }
            },
            // 其他弹窗表单
            formDatas: {}
            // 表单相关结束 -----------------------------------------------------------
        };
    },
    watch: {
        clients(newval, oldval) {
            let _obj = that.form1.props.columns.find(x => x.key == 'client');
            that.$set(_obj, 'data', newval);
            let _obj1 = that.queryForm1.columns.find(x => x.key == 'client');
            that.$set(_obj1, 'data', newval);

            // 同样更新酶抑制表单中的数据
            let _objEnzyme = that.enzyme_form.props.columns.find(x => x.key == 'client');
            that.$set(_objEnzyme, 'data', newval);
        },
        detection_categorys(newval, oldval) {
            let _obj = that.form1.props.columns.find(x => x.key == 'detection_category');
            that.$set(_obj, 'data', newval);
        },
        goods(newval, oldval) {
            let _obj = that.aquatic_form.props.columns.find(x => x.key == 'samplename');
            that.$set(_obj, 'data', newval);
        },
        'form1.data.sample_list'(newval, oldval) {
            if (that.$fn.isNotNull(newval)) {
                that.form1.props.columns.forEach(element => {
                    that.$set(element, 'disabled', true);
                });
            } else {
                that.form1.props.columns.forEach(element => {
                    if (element.key != 'detection_user') that.$set(element, 'disabled', false);
                });
            }
        },
        'aquatic_form.data.sample_list'(newval, oldval) {
            if (that.$fn.isNotNull(newval)) {
                that.aquatic_form.props.columns.forEach(element => {
                    if (element.key != 'sampleno' && element.key != 'contact' && element.key != 'contact_number' && element.key != 'address' && element.key != 'submituser_address') that.$set(element, 'disabled', true);
                });
            } else {
                that.aquatic_form.props.columns.forEach(element => {
                    if (element.key != 'detection_user') that.$set(element, 'disabled', false);
                });
            }
        },
        'enzyme_form.data.sample_list'(newval, oldval) {
            if (that.$fn.isNotNull(newval)) {
                that.enzyme_form.props.columns.forEach(element => {
                    if (element.key != 'contact' && element.key != 'contact_number' && element.key != 'submituser_address')
                        that.$set(element, 'disabled', true);
                });
            } else {
                that.enzyme_form.props.columns.forEach(element => {
                    if (element.key != 'detection_user') that.$set(element, 'disabled', false);
                });
            }
        }
    },
    // 监听 - 页面每次【加载时】执行(如：前进)
    onLoad(options = {}) {
        that = this;
        vk = that.vk;
        that.options = options;
        that.init(options);
        // console.log(vk.getVuex('$user.userInfo'));
    },
    onUnload() {
        // 返回false阻止页面被销毁
        return false;
    },
    // 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
    onReady() { },
    // 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
    onShow() { },
    // 监听 - 页面每次【隐藏时】执行(如：返回)
    onHide() { },
    // 函数
    methods: {
        mychange(val, formData, column, index, option) {
            // console.log(formData)
            // console.log(option)
        },
        // 页面数据初始化函数
        async init(options) {
            originalForms['form1'] = vk.pubfn.copyObject(that.form1);
            originalForms['aquatic_form'] = vk.pubfn.copyObject(that.aquatic_form);
            originalForms['enzyme_form'] = vk.pubfn.copyObject(that.enzyme_form);
            this.queryForm1.formData = options;
            let delivery_company = undefined,
                btns = [];
            if (!this.$hasRole('admin')) {
                delivery_company = vk.getVuex('$user.userInfo').delivery_company;
                if (this.$hasPermission('detection-form-edit')) {
                    btns.push('update');
                }
                if (this.$hasPermission('detection-form-del')) {
                    btns.push('delete');
                }
            } else {
                btns = ['update', 'delete'];
            }
            that.table1.btn = btns;

            vk.callFunction({
                url: `admin/base/client/sys/getalllist`,
                need_user_info: false,
                data: {
                    page: 1,
                    pageSize: 9999
                },
                success: data => {
                    this.clients = data.rows;
                }
            });
            vk.callFunction({
                url: 'admin/base/detection_category/sys/getList',
                data: {
                    page: 1,
                    pageSize: -1
                },
                success: data => {
                    this.detection_categorys = data.rows;
                }
            });

            await vk.callFunction({
                url: 'admin/base/goods/sys/getList',
                data: {
                    pageIndex: 1,
                    pageSize: 999
                },
                success: data => {
                    this.goods = concat(this.goods, data.rows);
                }
            });
            await vk.callFunction({
                url: 'admin/base/goods/sys/getList',
                data: {
                    pageIndex: 2,
                    pageSize: 999
                },
                success: data => {
                    this.goods = concat(this.goods, data.rows);
                }
            });
            await vk.callFunction({
                url: 'admin/base/goods/sys/getList',
                data: {
                    pageIndex: 3,
                    pageSize: 999
                },
                success: data => {
                    this.goods = concat(this.goods, data.rows);
                }
            });
            await vk.callFunction({
                url: 'admin/base/goods/sys/getList',
                data: {
                    pageIndex: 4,
                    pageSize: 999
                },
                success: data => {
                    this.goods = concat(this.goods, data.rows);
                }
            });
        },
        clients_fomattr(val, row, column, index) {
            // console.log(this.categories.find(x=>x._id==val))
            return this.clients.find(x => x._id == val).name;
        },
        detection_categorys_fomattr(val, row, column, index) {
            // console.log(this.categories.find(x=>x._id==val))
            return this.detection_categorys.find(x => x._id == val).name;
        },
        // 页面跳转
        pageTo(path) {
            vk.navigateTo(path);
        },
        // 表单重置
        resetForm() {
            vk.pubfn.resetForm(originalForms, that);
        },
        // 搜索
        search() {
            that.$refs.table1.search();
        },
        // 刷新
        refresh() {
            that.$refs.table1.refresh();
        },
        // 获取当前选中的行的数据
        getCurrentRow() {
            return that.$refs.table1.getCurrentRow();
        },
        // 监听 - 行的选中高亮事件
        currentChange(val) {
            that.table1.selectItem = val;
        },
        // 当选择项发生变化时会触发该事件
        selectionChange(list) {
            that.table1.multipleSelection = list;
        },
        // 显示添加页面
        addBtn(type) {
            that.resetForm();
            if (that.$refs.xTable != undefined) {
                that.$refs.xTable.reloadData([]);
            }
            if (that.$refs.xAQTable != undefined) {
                that.$refs.xAQTable.reloadData([]);
            }
            if (that.$refs.xEnzymeTable != undefined) {
                that.$refs.xEnzymeTable.reloadData([]);
            }

            that.form1.props.action = 'admin/testing/detection-form/sys/add';
            that.aquatic_form.props.action = 'admin/testing/detection-form/sys/add';
            that.enzyme_form.props.action = 'admin/testing/detection-form/sys/add';

            that.form1.props.formType = 'add';
            that.aquatic_form.props.formType = 'add';
            that.enzyme_form.props.formType = 'add';

            that.form1.props.title = '添加';
            that.aquatic_form.props.title = '添加(水产)';
            that.enzyme_form.props.title = '添加(酶抑制)';

            if (type == 'aquatic') {
                that.$set(that.aquatic_form.props, 'show', true);
            } else if (type == 'enzyme') {
                that.$set(that.enzyme_form.props, 'show', true);
            } else {
                that.form1.props.show = true;
            }

            that.$set(that.form1.data, 'type', type);
            that.$set(that.aquatic_form.data, 'type', type);
            that.$set(that.enzyme_form.data, 'type', 'enzyme');
        },
        // 显示修改页面
        updateBtn({ item }) {
            that.form1.props.action = 'admin/testing/detection-form/sys/update';
            that.aquatic_form.props.action = 'admin/testing/detection-form/sys/update';
            that.enzyme_form.props.action = 'admin/testing/detection-form/sys/update';

            that.form1.props.formType = 'update';
            that.aquatic_form.props.formType = 'update';
            that.enzyme_form.props.formType = 'update';

            that.form1.props.title = '编辑';
            that.aquatic_form.props.title = '编辑(水产)';
            that.enzyme_form.props.title = '编辑(酶抑制)';

            if (that.$fn.isNotNull(item.type) && item.type == 'aquatic') {
                that.aquatic_form.data = item;
                vk.callFunction({
                    url: 'admin/base/goods/sys/getsingel',
                    data: {
                        _id: item.sample_id
                    },
                    success: data => {
                        let _arry = that.detection_categorys.filter(x => data.data.detection_category.includes(x._id));
                        that.$set(that.aquatic_form.data, 'detection_category_list', _arry);
                    }
                });
                that.aquatic_form.props.show = true;
            } else if (that.$fn.isNotNull(item.type) && item.type == 'enzyme') {
                that.enzyme_form.data = item;
                that.enzyme_form.props.show = true;
            } else {
                that.form1.props.show = true;
                that.form1.data = item;
            }
        },
        // 删除按钮
        deleteBtn({ item, deleteFn }) {
            deleteFn({
                action: 'admin/testing/detection-form/sys/delete',
                data: {
                    _id: item._id
                }
            });
        },
        // 监听 - 批量操作的按钮点击事件
        batchBtn(index) {
            switch (index) {
                case 1:
                    this.mutifiPrint();
                    break;
                case 2:
                    this.mutifiDel();
                    break;
                default:
                    break;
            }
        },

        mutifiPrint() {
            // 分类存储不同类型的报告
            let normalReports = [];
            let aquaticReports = [];
            let enzymeReports = [];

            // 过滤并分类报告
            let _printdt = that.table1.multipleSelection.filter(x => that.isDateBeforeOrEqualToToday(x.detect_time));

            _printdt.forEach(item => {
                if (vk.pubfn.isNotNull(item.type) && item.type == 'aquatic') {
                    aquaticReports.push(vk.pubfn.deepClone(item));
                } else if (vk.pubfn.isNotNull(item.type) && item.type == 'enzyme') {
                    enzymeReports.push(vk.pubfn.deepClone(item));
                } else {
                    normalReports.push(vk.pubfn.deepClone(item));
                }
            });

            // 根据报告类型显示对应的打印弹窗
            if (normalReports.length > 0) {
                that.print.printData = normalReports;
                that.print.show = true;
            }

            if (aquaticReports.length > 0) {
                that.print_aquatic.printData = aquaticReports;
                that.print_aquatic.show = true;
            }

            if (enzymeReports.length > 0) {
                that.print_enzyme.printData = enzymeReports;
                that.print_enzyme.show = true;
            }
        },
        mutifiDel() {
            let _delids = that.table1.multipleSelection.map(x => x._id);
            vk.callFunction({
                url: 'admin/testing/detection-form/sys/batchdel',
                title: '请求中...',
                data: {
                    ids: _delids
                },
                success: data => { }
            });
        },
        activeCellMethod({ row, rowIndex }) {
            if (row.isSave != undefined && row.isSave == 1) return false;
            else return true;
        },
        getshowrows() {
            const $table = this.$refs.xTable;
            let _rows = [];
            const { insertRecords } = $table.getRecordset();
            if (this.$fn.isNull(this.form1.data.sample_list)) {
                this.form1.data.sample_list = [];
            }

            if (this.form1.data.sample_list.length > 0) _rows = concat(this.form1.data.sample_list, insertRecords).filter(x => that.$fn.isNull(x.isdel) || !x.isdel);
            else _rows = insertRecords;
            let _orderrows = orderBy(_rows, 'sampleno', 'asc');
            return _orderrows;
        },
        async insertEvent(row) {
            const $table = this.$refs.xTable;

            const record = {
                detection_category: '',
                rowNo: vk.pubfn.createOrderNo('ROW', 25),
                result: `阴性`,
                result_value: 1,
                yxresult: '阴性',
                samplename: ''
            };
            //获取实际的行数
            let _rows = this.getshowrows();
            const getcatename = rows => {
                rows = orderBy(rows, ['orderno', 'sampleno']);
                console.log(rows);
                for (let i = rows.length - 1; i >= 0; i--) {
                    let _cate_name = rows[i].detection_category;

                    if (this.$fn.isNotNull(_cate_name)) {
                        return _cate_name;
                    }
                }
            };
            if (this.$fn.isNotNull(_rows) && _rows.length > 0) {
                let _cate_name = getcatename(_rows);
                if (this.$fn.isNotNull(_cate_name)) {
                    let _bh = pinyin.getCamelChars(_cate_name);
                    this.$set(record, `sampleno`, _bh + this.padToThreeDigits(_rows.length + 1));
                }
            }
            let _data = $table.getTableData();
            if (this.$fn.isNotNull(_data.fullData)) {
                this.$set(record, `orderno`, _data.fullData.length + 1);
            } else {
                this.$set(record, `orderno`, 1);
            }

            const { row: newRow } = await $table.insertAt(record, row);

            this.$nextTick(async () => {
                $table.scrollToRow(newRow);
                await $table.setCurrentRow(newRow);
                await $table.setEditCell(newRow, 'sampleno');
                if (this.$fn.isNotNull(document.getElementById(`input_${newRow.rowNo}`))) {
                    let e = document.getElementById(`input_${newRow.rowNo}`).querySelector('.vxe-input--inner');

                    if (e) {
                        e.focus();
                        if (e.select != undefined) e.select();
                        e.click();
                    }
                }
            });
        },
        async removeEvent(row) {
            const $table = this.$refs.xTable;
            $table.remove(row);
        },

        getCurrentDate() {
            const today = new Date();
            const year = today.getFullYear();
            const month = (today.getMonth() + 1).toString().padStart(2, '0');
            const day = today.getDate().toString().padStart(2, '0');
            return `${year}${month}${day}`;
        },
        marksur(row) {
            if (this.$fn.isNull(row.samplename)) {
                vk.alert(`样品名称不能为空`);
                return;
            }
            if (this.$fn.isNull(row.result)) {
                vk.alert(`检测结论不能为空`);
                return;
            }
            that.$set(row, 'isSave', 1);
        },

        mark_aquatic_sur(row) {
            if (this.$fn.isNull(row.detection_category)) {
                vk.alert(`检测项目不能为空`);
                return;
            }
            if (this.$fn.isNull(row.result)) {
                vk.alert(`检测结论不能为空`);
                return;
            }
            that.$set(row, 'isSave', 1);
        },

        mark_enzyme_sur(row) {
            if (this.$fn.isNull(row.detection_category)) {
                vk.alert(`检测项目不能为空`);
                return;
            }
            if (this.$fn.isNull(row.result)) {
                vk.alert(`检测结论不能为空`);
                return;
            }
            if (this.$fn.isNull(row.inhibition_rate)) {
                vk.alert(`抑制率不能为空`);
                return;
            }
            that.$set(row, 'isSave', 1);
        },

        isDateBeforeOrEqualToToday(item) {
            // 创建一个表示给定日期的Date对象
            const dateToCheck = new Date(item);
            dateToCheck.setHours(0, 0, 0, 0);

            // 创建一个表示今天的Date对象
            const today = new Date();

            // 将今天的日期设置为当天的开始（即00:00:00）
            today.setHours(0, 0, 0, 0);

            // 比较两个日期的时间戳
            return dateToCheck <= today;
        },
        importBtn() { },
        orderBy(list, arry, type) {
            let _result = orderBy(list, arry, type);
            return _result;
        },
        handleFileChange(ss) {
            // 获取选择的文件对象
            const file = ss.raw;
            // 创建 FileReader 对象
            const reader = new FileReader();
            let that = this;
            // 定义读取文件完成后的回调函数
            reader.onload = async e => {
                // 获取文件的二进制数据
                const data = e.target.result;
                // 解析文件数据，获取工作簿对象
                const workbook = XLSX.read(data, { type: 'binary' });
                // 获取工作簿中的第一个工作表名称
                const sheetName = workbook.SheetNames[0];
                // 获取工作簿中的第一个工作表对象
                const sheet = workbook.Sheets[sheetName];
                // 将工作表对象转换为 JSON 格式的数据
                const jsonData = XLSX.utils.sheet_to_json(sheet, { range: 1, header: 'A' });
                // 定义一个空数组，用于存储读取的列的值
                const columnData = [];
                const columnHeader = {};
                try {
                    let tenancy = new Date().getTime();
                    // 遍历 JSON 数据
                    let _rowindex = 1;
                    jsonData.forEach((row, index) => {
                        //   console.log(row);
                        //   console.log(this.clients);
                        let _dd = row['A'];
                        let _client_name = row['B'].trim();
                        let _goods_name = row['C'].trim();
                        let det_category_name = row['E'].trim();
                        let _client = find(this.clients, x => x.name == _client_name);
                        let _goods = find(this.goods, x => x.name == _goods_name);
                        let _det_cate = find(this.detection_categorys, x => x.name == det_category_name);
                        if (this.$fn.isNull(_client)) {
                            throw new Error(`第${_rowindex}行系统不存在${_client_name}这个委托单位/人,请检查!`);
                        }
                        if (this.$fn.isNull(_goods)) {
                            throw new Error(`第${_rowindex}行系统不存在${_goods_name}这个样品名称,请检查!`);
                        }
                        if (this.$fn.isNull(_det_cate)) {
                            throw new Error(`第${_rowindex}行系统不存在${det_category_name}这个检测项目,请检查!`);
                        }
                        if (!this.$hasRole('admin') && !this.$hasRole('ROLE_ZZ')) {
                            if (this.$fn.isNull(vk.getVuex('$user.userInfo').delivery_company)) {
                                throw new Error(`你没有导入任何配送公司权限,请联系管理员分配`);
                            }
                            if (!includes(vk.getVuex('$user.userInfo').delivery_company, _client._id)) {
                                throw new Error(`当前用户没有导入${_client_name}权限,请联系管理员分配`);
                            }
                        }

                        let addobj = find(columnData, x => x._dd == _dd);

                        if (this.$fn.isNull(addobj)) {
                            addobj = {};
                            this.$set(addobj, '_dd', _dd);
                            this.$set(addobj, 'sample_list', []);
                            this.$set(addobj, 'detection_type', row['D']);
                            this.$set(addobj, 'detection_category', _det_cate._id);
                            this.$set(addobj, 'detection_standard_name', _det_cate.name);
                            this.$set(addobj, 'detection_standard', _det_cate.standard);
                            this.$set(addobj, 'client', _client._id);
                            this.$set(addobj, 'client_name', _client_name);
                            this.$set(addobj, 'address', _client.address);
                            this.$set(addobj, 'detection_user', row['G']);
                            this.$set(addobj, 'submitUser', row['F']);
                            this.$set(addobj, 'submituser_address', row['I']);
                            this.$set(addobj, 'detect_time', new Date().getTime());

                            let _sample = {};
                            let _bh = pinyin.getCamelChars(addobj.detection_standard_name) + '001';
                            this.$set(_sample, 'sampleno', _bh);
                            this.$set(_sample, 'samplename', _goods_name);
                            this.$set(_sample, 'sample_id', _goods._id);
                            this.$set(_sample, 'detection_category', _det_cate.name);

                            this.$set(_sample, 'detection_standard', _det_cate.standard);
                            this.$set(_sample, 'detection_include', _det_cate.detection_include);
                            this.$set(_sample, 'result', `阴性`);
                            this.$set(_sample, 'yxresult', '阴性');
                            this.$set(_sample, 'remark', row['H']);
                            this.$set(_sample, 'isSave', 1);
                            addobj.sample_list.push(_sample);
                            columnData.push(addobj);
                        } else {
                            let _sample = {};
                            let _bh = pinyin.getCamelChars(addobj.detection_standard_name) + this.padToThreeDigits(addobj.sample_list.length + 1);
                            this.$set(_sample, 'sampleno', _bh);
                            this.$set(_sample, 'samplename', _goods_name);
                            this.$set(_sample, 'sample_id', _goods._id);
                            this.$set(_sample, 'detection_category', _det_cate.name);
                            this.$set(_sample, 'detection_standard', _det_cate.standard);
                            this.$set(_sample, 'detection_include', _det_cate.detection_include);
                            this.$set(_sample, 'result', `阴性`);
                            this.$set(_sample, 'yxresult', '阴性');
                            this.$set(_sample, 'remark', row['H']);

                            this.$set(_sample, 'isSave', 1);
                            addobj.sample_list.push(_sample);
                        }

                        _rowindex++;
                    });
                } catch (error) {
                    vk.alert(error.message);
                    return;
                }

                vk.callFunction({
                    url: 'admin/testing/detection-form/sys/batchadd',
                    title: '请求中...',
                    data: {
                        batch_datas: columnData
                    },
                    success: data => {
                        vk.alert(`导入成功`);

                        this.$refs.table1.refresh();
                    }
                });
            };
            this.fileList = [];
            // 读取文件内容
            reader.readAsBinaryString(file);
        },
        padToThreeDigits(num) {
            // 将输入的数字转换为字符串
            const strNum = num.toString();

            // 使用padStart方法在字符串前面填充零，直到长度为3
            return strNum.padStart(3, '0');
        },
        handelSampleChane(val, form, row) {
            let list = [];
            if (this.$fn.isNotNull(form.detection_category)) {
                list = this.detection_categorys.filter(x => form.detection_category.includes(x._id));
            }
            this.$set(row, 'category_list', list);
            //console.log(val, form, row);
        },
        handelDetection_categoryChane(val, form, row) {
            row.detection_standard = form.standard;
            row.detection_category = form.name;
            row.detection_include = form.detection_include;

            //row. = form.standardRequir;
            let _bh = pinyin.getCamelChars(row.detection_category);

            if (this.$fn.isNotNull(row.sampleno)) {
                let match = row.sampleno.match(/^[^0-9]+/);
                if (match != _bh) {
                    this.$set(row, `sampleno`, _bh + '001');
                }
            } else {
                this.$set(row, `sampleno`, _bh + '001');
            }
            // let _bh = pinyin.getCamelChars(row.detection_category)
            // this.$set(row, `sampleno`, _bh)
        },

        // 批量设置常规表单检测项目时使用，不修改已有样品编号
        batchSetNormalDetectionChange(val, form, row) {
            row.detection_standard = form.standard;
            row.detection_category = form.name;
            row.detection_include = form.detection_include;

            // 只有当样品编号为空时才生成新编号
            if (this.$fn.isNull(row.sampleno) || row.sampleno.trim() === '') {
                let _bh = pinyin.getCamelChars(row.detection_category);
                this.$set(row, `sampleno`, _bh + '001');
            }
            // 如果已有样品编号，则保留不变
        },
        handelEnzymeDetectionChange(val, form, row) {
            row.detection_standard = form.standard;
            row.detection_category = form.name;
            row.detection_include = form.detection_include;
            row.standard_limit = "<50";

            let _bh = pinyin.getCamelChars(row.detection_category);

            if (this.$fn.isNotNull(row.sampleno)) {
                let match = row.sampleno.match(/^[^0-9]+/);
                if (match != _bh) {
                    this.$set(row, `sampleno`, _bh + '001');
                }
            } else {
                this.$set(row, `sampleno`, _bh + '001');
            }
        },

        // 批量设置检测项目时使用，不修改已有样品编号
        batchSetEnzymeDetectionChange(val, form, row) {
            row.detection_standard = form.standard;
            row.detection_category = form.name;
            row.detection_include = form.detection_include;
            row.standard_limit = "<50";

            // 只有当样品编号为空时才生成新编号
            if (this.$fn.isNull(row.sampleno) || row.sampleno.trim() === '') {
                let _bh = pinyin.getCamelChars(row.detection_category);
                this.$set(row, `sampleno`, _bh + '001');
            }
            // 如果已有样品编号，则保留不变
        },
        async insertAquaticEvent(row) {
            const $table = this.$refs.xAQTable;

            const record = {
                detection_category: '',
                rowNo: vk.pubfn.createOrderNo('ROW', 25),
                result: `阴性`,
                result_value: 1,
                yxresult: '阴性',
                samplename: '',
                //standardRequir: '不得检出'
            };

            let _data = $table.getTableData();
            if (this.$fn.isNotNull(_data.fullData)) {
                this.$set(record, `orderno`, _data.fullData.length + 1);
            } else {
                this.$set(record, `orderno`, 1);
            }

            const { row: newRow } = await $table.insertAt(record, row);

            this.$nextTick(async () => {
                $table.scrollToRow(newRow);
                await $table.setCurrentRow(newRow);
                await $table.setEditCell(newRow, 'detection_category');
                if (this.$fn.isNotNull(document.getElementById(`input_${newRow.rowNo}`))) {
                    let e = document.getElementById(`input_${newRow.rowNo}`).querySelector('.vxe-input--inner');

                    if (e) {
                        e.focus();
                        if (e.select != undefined) e.select();
                        e.click();
                    }
                }
            });
        },
        async removeAquaticEvent(row) {
            const $table = this.$refs.xAQTable;
            $table.remove(row);
        },
        handel_AQ_detection_categoryChange(val, form, row) {
            row.detection_standard = form.standard;
            row.detection_category = form.name;
            row.detection_include = form.detection_include;
            row.standardRequir = form.standardRequir;
        },

        // 批量设置水产表单检测项目时使用（水产表单本身不修改样品编号，所以可以直接使用原方法）
        batchSetAquaticDetectionChange(val, form, row) {
            this.handel_AQ_detection_categoryChange(val, form, row);
        },

        // 酶抑制表单相关方法
        async insertEnzymeEvent(row) {
            const $table = this.$refs.xEnzymeTable;

            const record = {
                detection_category: '',
                rowNo: vk.pubfn.createOrderNo('ROW', 25),
                result: `阴性`,
                result_value: 1,
                yxresult: '阴性',
                conclusion: '阴性',
                samplename: '',
                standard_limit: '<50',
                inhibition_rate: ''
            };

            let _data = $table.getTableData();
            if (this.$fn.isNotNull(_data.fullData)) {
                this.$set(record, `orderno`, _data.fullData.length + 1);
            } else {
                this.$set(record, `orderno`, 1);
            }

            const { row: newRow } = await $table.insertAt(record, row);

            this.$nextTick(async () => {
                $table.scrollToRow(newRow);
                await $table.setCurrentRow(newRow);
                await $table.setEditCell(newRow, 'sampleno');
                if (this.$fn.isNotNull(document.getElementById(`input_${newRow.rowNo}`))) {
                    let e = document.getElementById(`input_${newRow.rowNo}`).querySelector('.vxe-input--inner');

                    if (e) {
                        e.focus();
                        if (e.select != undefined) e.select();
                        e.click();
                    }
                }
            });
        },
        async removeEnzymeEvent(row) {
            const $table = this.$refs.xEnzymeTable;
            $table.remove(row);
        },
        isEnzymeInhibitionReport(item) {
            return vk.pubfn.isNotNull(item.type) && item.type === 'enzyme';
        },
        // 批量添加酶抑制样品
        batchAddEnzymeSamples() {
            // 第一步：输入样品编码前缀
            this.$prompt('请输入样品编码前缀（例如：rq2005）', '批量添加样品 - 步骤1/2', {
                confirmButtonText: '下一步',
                cancelButtonText: '取消',
                inputPattern: /^[a-zA-Z0-9]+$/,
                inputErrorMessage: '样品编码前缀只能包含字母和数字'
            }).then(({ value: prefix }) => {
                if (!prefix || prefix.trim() === '') {
                    this.$message.error('样品编码前缀不能为空');
                    return;
                }

                // 第二步：输入数量
                this.$prompt('请输入要添加的样品数量', '批量添加样品 - 步骤2/2', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /^[1-9]\d*$/,
                    inputErrorMessage: '请输入正整数'
                }).then(({ value: countStr }) => {
                    const count = parseInt(countStr);
                    if (count > 0) {
                        // 批量添加样品，传入前缀和数量
                        this.batchInsertEnzymeSamples(count, prefix.trim());
                        this.$message({
                            type: 'success',
                            message: `成功添加 ${count} 个样品，编号前缀：${prefix.trim()}`
                        });
                    }
                }).catch(() => {
                    // 用户取消输入数量
                });
            }).catch(() => {
                // 用户取消输入前缀
            });
        },

        // 批量插入酶抑制样品
        async batchInsertEnzymeSamples(count, prefix = '') {
            const $table = this.$refs.xEnzymeTable;

            // 获取当前表格数据
            let _data = $table.getTableData();
            let startOrderno = 1;
            let startSequenceNumber = 1; // 样品编号序列起始值

            if (this.$fn.isNotNull(_data.fullData) && _data.fullData.length > 0) {
                startOrderno = _data.fullData.length + 1;

                // 如果有前缀且表格中已有数据，检查是否需要继续编号
                if (prefix) {
                    // 查找最后一个非空的样品编号
                    let lastSampleNo = '';
                    for (let i = _data.fullData.length - 1; i >= 0; i--) {
                        if (this.$fn.isNotNull(_data.fullData[i].sampleno) && _data.fullData[i].sampleno.trim() !== '') {
                            lastSampleNo = _data.fullData[i].sampleno.trim();
                            break;
                        }
                    }

                    // 如果找到了最后一个样品编号，询问用户是否继续编号
                    if (lastSampleNo) {
                        try {
                            await this.$confirm(
                                `检测到表单中已存在样品，最后一个样品编号为：${lastSampleNo}\n\n是否继续上一轮编号？\n\n选择"确定"：继续上一轮编号累加\n选择"取消"：重新从001开始`,
                                '编号方式选择',
                                {
                                    confirmButtonText: '继续编号',
                                    cancelButtonText: '重新开始',
                                    type: 'question'
                                }
                            );

                            // 用户选择继续编号，尝试解析最后一个编号
                            // 匹配最后的3位数字序列号（如001, 002等）
                            const match = lastSampleNo.match(/(\d{3})$/);
                            if (match) {
                                const lastNumber = parseInt(match[1]);
                                startSequenceNumber = lastNumber + 1;
                            } else {
                                // 如果无法解析3位序列号，尝试匹配末尾的任意数字
                                const fallbackMatch = lastSampleNo.match(/(\d+)$/);
                                if (fallbackMatch) {
                                    const lastNumber = parseInt(fallbackMatch[1]);
                                    // 如果数字很大，可能包含了前缀中的数字，只取最后3位
                                    const lastThreeDigits = lastNumber % 1000;
                                    startSequenceNumber = lastThreeDigits + 1;
                                } else {
                                    // 如果完全无法解析编号，从1开始
                                    startSequenceNumber = 1;
                                }
                            }
                        } catch (error) {
                            // 用户选择重新开始，从1开始
                            startSequenceNumber = 1;
                        }
                    }
                }
            }

            // 批量创建样品记录
            for (let i = 0; i < count; i++) {
                // 生成样品编号：如果有前缀，则生成前缀+三位序号（如rq2005001），否则为空
                let sampleno = '';
                if (prefix) {
                    // 生成三位序号，从startSequenceNumber开始
                    const sequenceNumber = (startSequenceNumber + i).toString().padStart(3, '0');
                    sampleno = `${prefix}${sequenceNumber}`;
                }

                const record = {
                    detection_category: '',
                    rowNo: vk.pubfn.createOrderNo('ROW', 25),
                    result: `阴性`,
                    result_value: 1,
                    yxresult: '阴性',
                    conclusion: '阴性',
                    samplename: '',
                    sampleno: sampleno, // 设置生成的样品编号
                    standard_limit: '<50',
                    inhibition_rate: '',
                    orderno: startOrderno + i
                };

                // 插入记录
                await $table.insertAt(record, -1);
            }

            // 滚动到最后一行
            this.$nextTick(() => {
                if (_data.fullData && _data.fullData.length > 0) {
                    $table.scrollToRow(_data.fullData[_data.fullData.length - 1]);
                }
            });
        },

        // 批量录入样品名称
        batchInputSampleNames() {
            this.$prompt('请输入样品名称，多个名称用英文逗号分隔', '批量录入样品名称', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputPlaceholder: '例如：苹果,香蕉,橙子'
            }).then(({ value }) => {
                if (!value || value.trim() === '') {
                    this.$message.warning('请输入样品名称');
                    return;
                }

                // 分割样品名称
                const sampleNames = value.split(',').map(name => name.trim()).filter(name => name !== '');
                if (sampleNames.length === 0) {
                    this.$message.warning('请输入有效的样品名称');
                    return;
                }

                // 批量设置样品名称
                this.batchSetSampleNames(sampleNames);
            }).catch(() => {
                // 用户取消输入
            });
        },

        // 批量设置样品名称
        async batchSetSampleNames(sampleNames) {
            const $table = this.$refs.xEnzymeTable;
            let _data = $table.getTableData();
            let currentRows = _data.fullData || [];

            // 验证样品名称是否存在
            const validatedNames = [];
            const loading = this.$loading({
                lock: true,
                text: '正在验证样品名称...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            try {
                for (let i = 0; i < sampleNames.length; i++) {
                    const sampleName = sampleNames[i];

                    // 调用后台接口验证样品名称是否存在
                    const result = await this.validateSampleName(sampleName);
                    if (result.exists) {
                        validatedNames.push({
                            name: sampleName,
                            id: result.id,
                            valid: true
                        });
                    } else {
                        validatedNames.push({
                            name: sampleName,
                            id: null,
                            valid: false
                        });
                        this.$message.warning(`样品名称 "${sampleName}" 不存在，该位置将保持为空`);
                    }
                }
            } catch (error) {
                this.$message.error('验证样品名称时出错：' + error.message);
                return;
            } finally {
                loading.close();
            }

            // 如果需要的样品数量超过现有行数，自动添加新行
            const neededRows = validatedNames.length;
            const currentRowCount = currentRows.length;

            if (neededRows > currentRowCount) {
                const additionalRows = neededRows - currentRowCount;
                await this.batchInsertEnzymeSamples(additionalRows);
                // 重新获取表格数据
                _data = $table.getTableData();
                currentRows = _data.fullData || [];
            }

            // 设置样品名称
            for (let i = 0; i < validatedNames.length && i < currentRows.length; i++) {
                const validatedName = validatedNames[i];
                const row = currentRows[i];

                if (validatedName.valid) {
                    this.$set(row, 'samplename', validatedName.name);
                    this.$set(row, 'sample_id', validatedName.id);
                } else {
                    // 无效的样品名称，清空该行的样品名称
                    this.$set(row, 'samplename', '');
                    this.$set(row, 'sample_id', '');
                }
            }

            this.$message.success(`批量录入完成，共处理 ${validatedNames.length} 个样品名称`);
        },

        // 验证样品名称是否存在
        async validateSampleName(sampleName) {
            return new Promise((resolve, reject) => {
                vk.callFunction({
                    url: 'admin/base/goods/sys/getAllList',
                    data: {
                        searchvalue: sampleName,
                        exactMatch: true,  // 使用精确匹配
                        pageSize: 10
                    },
                    success: data => {
                        console.log('验证样品名称返回数据:', data); // 调试日志
                        if (data.rows && data.rows.length > 0) {
                            // 由于后台已经进行了精确匹配，直接取第一个结果
                            const exactMatch = data.rows[0];
                            console.log('找到精确匹配:', exactMatch); // 调试日志
                            resolve({
                                exists: true,
                                id: exactMatch._id,
                                data: exactMatch
                            });
                        } else {
                            console.log('搜索无结果'); // 调试日志
                            resolve({
                                exists: false,
                                id: null,
                                data: null
                            });
                        }
                    },
                    fail: error => {
                        console.error('验证样品名称失败:', error); // 调试日志
                        reject(error);
                    }
                });
            });
        },

        // 批量录入抑制率
        batchInputInhibitionRates() {
            this.$prompt('请输入抑制率数值，多个数值用英文逗号分隔', '批量录入抑制率', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputPlaceholder: '例如：15.5,23.8,8.2'
            }).then(({ value }) => {
                if (!value || value.trim() === '') {
                    this.$message.warning('请输入抑制率数值');
                    return;
                }

                // 分割抑制率数值
                const inhibitionRates = value.split(',').map(rate => rate.trim()).filter(rate => rate !== '');
                if (inhibitionRates.length === 0) {
                    this.$message.warning('请输入有效的抑制率数值');
                    return;
                }

                // 验证数值格式
                const validRates = [];
                const invalidRates = [];

                inhibitionRates.forEach((rate, index) => {
                    const numRate = parseFloat(rate);
                    if (isNaN(numRate)) {
                        invalidRates.push(`第${index + 1}个值"${rate}"`);
                        validRates.push('');
                    } else if (numRate < 0 || numRate > 100) {
                        invalidRates.push(`第${index + 1}个值"${rate}"(应在0-100之间)`);
                        validRates.push('');
                    } else {
                        validRates.push(numRate.toString());
                    }
                });

                if (invalidRates.length > 0) {
                    this.$message.warning(`以下数值格式不正确，对应位置将保持为空：${invalidRates.join(', ')}`);
                }

                // 批量设置抑制率
                this.batchSetInhibitionRates(validRates);
            }).catch(() => {
                // 用户取消输入
            });
        },

        // 批量设置抑制率
        async batchSetInhibitionRates(inhibitionRates) {
            const $table = this.$refs.xEnzymeTable;
            let _data = $table.getTableData();
            let currentRows = _data.fullData || [];

            // 如果需要的行数超过现有行数，自动添加新行
            const neededRows = inhibitionRates.length;
            const currentRowCount = currentRows.length;

            if (neededRows > currentRowCount) {
                const additionalRows = neededRows - currentRowCount;
                await this.batchInsertEnzymeSamples(additionalRows);
                // 重新获取表格数据
                _data = $table.getTableData();
                currentRows = _data.fullData || [];
            }

            // 设置抑制率
            for (let i = 0; i < inhibitionRates.length && i < currentRows.length; i++) {
                const rate = inhibitionRates[i];
                const row = currentRows[i];

                if (rate !== '') {
                    this.$set(row, 'inhibition_rate', rate);

                    // 根据抑制率自动设置判定结论
                    const numRate = parseFloat(rate);
                    if (numRate >= 50) {
                        // 抑制率>=50%，判定为阳性
                        this.$set(row, 'result_value', 0);
                        this.$set(row, 'result', '阳性');
                        this.$set(row, 'yxresult', '阳性');
                        this.$set(row, 'conclusion', '阳性');
                    } else {
                        // 抑制率<50%，判定为阴性
                        this.$set(row, 'result_value', 1);
                        this.$set(row, 'result', '阴性');
                        this.$set(row, 'yxresult', '阴性');
                        this.$set(row, 'conclusion', '阴性');
                    }
                }
            }

            this.$message.success(`批量录入完成，共处理 ${inhibitionRates.length} 个抑制率数值`);
        },

        // 一键确认所有未确认样品
        batchConfirmAllSamples(formType) {
            let tableRef, samples, formTypeName;

            // 根据表单类型确定相关参数
            switch (formType) {
                case 'normal':
                    tableRef = this.$refs.xTable;
                    formTypeName = '常规检测';
                    break;
                case 'aquatic':
                    tableRef = this.$refs.xAQTable;
                    formTypeName = '水产检测';
                    break;
                case 'enzyme':
                    tableRef = this.$refs.xEnzymeTable;
                    formTypeName = '酶抑制检测';
                    break;
                default:
                    this.$message.error('未知的表单类型');
                    return;
            }

            if (!tableRef) {
                this.$message.warning('表格未初始化');
                return;
            }

            const _data = tableRef.getTableData();
            samples = _data.fullData || [];

            if (samples.length === 0) {
                this.$message.warning('没有样品数据');
                return;
            }

            // 筛选出未确认的样品
            const unconfirmedSamples = samples.filter(sample =>
                this.$fn.isNull(sample.isSave) || sample.isSave !== 1
            );

            if (unconfirmedSamples.length === 0) {
                this.$message.info('所有样品都已确认');
                return;
            }

            // 确认提示
            this.$confirm(
                `确定要一键确认所有未确认的${formTypeName}样品吗？\n共有 ${unconfirmedSamples.length} 个样品待确认。`,
                '确认操作',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                // 执行批量确认
                let successCount = 0;
                let failCount = 0;
                const errors = [];

                unconfirmedSamples.forEach((sample, index) => {
                    // 手动验证每个样品，避免使用会抛出异常的 vk.alert
                    let validationError = null;

                    if (formType === 'normal') {
                        if (this.$fn.isNull(sample.samplename)) {
                            validationError = '样品名称不能为空';
                        } else if (this.$fn.isNull(sample.result)) {
                            validationError = '检测结论不能为空';
                        }
                    } else if (formType === 'aquatic') {
                        if (this.$fn.isNull(sample.detection_category)) {
                            validationError = '检测项目不能为空';
                        } else if (this.$fn.isNull(sample.result)) {
                            validationError = '检测结论不能为空';
                        }
                    } else if (formType === 'enzyme') {
                        if (this.$fn.isNull(sample.detection_category)) {
                            validationError = '检测项目不能为空';
                        } else if (this.$fn.isNull(sample.result)) {
                            validationError = '检测结论不能为空';
                        } else if (this.$fn.isNull(sample.inhibition_rate)) {
                            validationError = '抑制率不能为空';
                        }
                    }

                    if (validationError) {
                        failCount++;
                        errors.push(`第${index + 1}行: ${validationError}`);
                    } else {
                        // 直接设置确认状态，避免调用会抛出异常的方法
                        that.$set(sample, 'isSave', 1);
                        successCount++;
                    }
                });

                // 显示结果
                if (failCount === 0) {
                    this.$message.success(`成功确认 ${successCount} 个样品`);
                } else {
                    this.$message.warning(`确认完成：成功 ${successCount} 个，失败 ${failCount} 个`);
                    if (errors.length > 0) {
                        console.warn('确认失败的样品:', errors);
                        // 显示前3个错误信息
                        const displayErrors = errors.slice(0, 3);
                        this.$message.error(`部分样品确认失败：\n${displayErrors.join('\n')}`);
                    }
                }
            }).catch(() => {
                // 用户取消操作
            });
        },

        // 批量设置常规表单检测项目
        batchSetNormalDetectionCategory() {
            const $table = this.$refs.xTable;
            if (!$table) {
                this.$message.warning('表格未初始化');
                return;
            }

            const _data = $table.getTableData();
            const samples = _data.fullData || [];

            if (samples.length === 0) {
                this.$message.warning('没有样品数据');
                return;
            }

            // 获取第一个样品的检测项目列表作为选项
            let detectionOptions = [];
            if (samples.length > 0 && samples[0].category_list) {
                detectionOptions = samples[0].category_list;
            } else {
                // 如果没有category_list，使用全局的detection_categorys
                detectionOptions = this.detection_categorys;
            }

            if (detectionOptions.length === 0) {
                this.$message.warning('没有可选的检测项目');
                return;
            }

            // 重置选择值
            this.selectedDetectionCategory = '';

            // 创建选择框的HTML
            const selectHtml = `
                <div style="margin-top: 10px;">
                    <p style="margin-bottom: 10px;">请选择要设置的检测项目：</p>
                    <select id="detectionCategorySelect" style="width: 100%; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
                        <option value="">请选择检测项目</option>
                        ${detectionOptions.map(item => `<option value="${item._id}">${item.name}</option>`).join('')}
                    </select>
                </div>
            `;

            // 弹出选择对话框
            this.$msgbox({
                title: '批量设置检测项目',
                dangerouslyUseHTMLString: true,
                message: selectHtml,
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        const selectElement = document.getElementById('detectionCategorySelect');
                        const selectedValue = selectElement ? selectElement.value : '';

                        if (!selectedValue) {
                            this.$message.warning('请选择检测项目');
                            return false;
                        }

                        // 找到选中的检测项目
                        const selectedCategory = detectionOptions.find(item => item._id === selectedValue);
                        if (!selectedCategory) {
                            this.$message.warning('选择的检测项目无效');
                            return false;
                        }

                        // 批量设置检测项目
                        samples.forEach(row => {
                            this.batchSetNormalDetectionChange(selectedCategory._id, selectedCategory, row);
                        });

                        this.$message.success(`成功为 ${samples.length} 个样品设置检测项目：${selectedCategory.name}`);
                        done();
                    } else {
                        done();
                    }
                }
            });
        },

        // 批量设置水产表单检测项目
        batchSetAquaticDetectionCategory() {
            const $table = this.$refs.xAQTable;
            if (!$table) {
                this.$message.warning('表格未初始化');
                return;
            }

            const _data = $table.getTableData();
            const samples = _data.fullData || [];

            if (samples.length === 0) {
                this.$message.warning('没有样品数据');
                return;
            }

            // 获取水产表单的检测项目列表
            const detectionOptions = this.aquatic_form.data.detection_category_list || [];

            if (detectionOptions.length === 0) {
                this.$message.warning('没有可选的检测项目，请先选择样品');
                return;
            }

            // 重置选择值
            this.selectedAquaticDetectionCategory = '';

            // 创建选择框的HTML
            const selectHtml = `
                <div style="margin-top: 10px;">
                    <p style="margin-bottom: 10px;">请选择要设置的检测项目：</p>
                    <select id="aquaticDetectionCategorySelect" style="width: 100%; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
                        <option value="">请选择检测项目</option>
                        ${detectionOptions.map(item => `<option value="${item._id}">${item.name}</option>`).join('')}
                    </select>
                </div>
            `;

            // 弹出选择对话框
            this.$msgbox({
                title: '批量设置检测项目',
                dangerouslyUseHTMLString: true,
                message: selectHtml,
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        const selectElement = document.getElementById('aquaticDetectionCategorySelect');
                        const selectedValue = selectElement ? selectElement.value : '';

                        if (!selectedValue) {
                            this.$message.warning('请选择检测项目');
                            return false;
                        }

                        // 找到选中的检测项目
                        const selectedCategory = detectionOptions.find(item => item._id === selectedValue);
                        if (!selectedCategory) {
                            this.$message.warning('选择的检测项目无效');
                            return false;
                        }

                        // 批量设置检测项目
                        samples.forEach(row => {
                            this.batchSetAquaticDetectionChange(selectedCategory._id, selectedCategory, row);
                        });

                        this.$message.success(`成功为 ${samples.length} 个样品设置检测项目：${selectedCategory.name}`);
                        done();
                    } else {
                        done();
                    }
                }
            });
        },

        // 批量设置酶抑制表单检测项目
        batchSetDetectionCategory() {
            const $table = this.$refs.xEnzymeTable;
            if (!$table) {
                this.$message.warning('表格未初始化');
                return;
            }

            const _data = $table.getTableData();
            const samples = _data.fullData || [];

            if (samples.length === 0) {
                this.$message.warning('没有样品数据');
                return;
            }

            // 获取第一个样品的检测项目列表作为选项
            let detectionOptions = [];
            if (samples.length > 0 && samples[0].category_list) {
                detectionOptions = samples[0].category_list;
            } else {
                // 如果没有category_list，使用全局的detection_categorys
                detectionOptions = this.detection_categorys;
            }

            if (detectionOptions.length === 0) {
                this.$message.warning('没有可选的检测项目');
                return;
            }

            // 重置选择值
            this.selectedEnzymeDetectionCategory = '';

            // 创建选择框的HTML
            const selectHtml = `
                <div style="margin-top: 10px;">
                    <p style="margin-bottom: 10px;">请选择要设置的检测项目：</p>
                    <select id="enzymeDetectionCategorySelect" style="width: 100%; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
                        <option value="">请选择检测项目</option>
                        ${detectionOptions.map(item => `<option value="${item._id}">${item.name}</option>`).join('')}
                    </select>
                </div>
            `;

            // 弹出选择对话框
            this.$msgbox({
                title: '批量设置检测项目',
                dangerouslyUseHTMLString: true,
                message: selectHtml,
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        const selectElement = document.getElementById('enzymeDetectionCategorySelect');
                        const selectedValue = selectElement ? selectElement.value : '';

                        if (!selectedValue) {
                            this.$message.warning('请选择检测项目');
                            return false;
                        }

                        // 找到选中的检测项目
                        const selectedCategory = detectionOptions.find(item => item._id === selectedValue);
                        if (!selectedCategory) {
                            this.$message.warning('选择的检测项目无效');
                            return false;
                        }

                        // 批量设置检测项目
                        samples.forEach(row => {
                            this.batchSetEnzymeDetectionChange(selectedCategory._id, selectedCategory, row);
                        });

                        this.$message.success(`成功为 ${samples.length} 个样品设置检测项目：${selectedCategory.name}`);
                        done();
                    } else {
                        done();
                    }
                }
            });
        }
    },

    // 过滤器
    filters: {},
    // 计算属性
    computed: {
        canAdd: function () {
            // 依赖 a 和 b，当 a 或 b 的值变化时，这个计算属性会重新计算
            return this.$fn.isNotNull(this.form1.data.client) && this.$fn.isNotNull(this.form1.data.detection_type) && this.$fn.isNotNull(this.form1.data.submitUser);
            // && this.$fn.isNotNull(this.form1.data.detection_category)
            // && this.$fn.isNotNull(this.form1.data.detection_standard)
        },
        goodsfilters: function () {
            return this.goods;
            //return this.goods.filter(x => includes(x.detection_category, this.form1.data.detection_category))
        }
    }
};
</script>

<style lang="scss" scoped>
.page-body {}

.vxe-input--panel.type--date,
.vxe-input--panel.type--month,
.vxe-input--panel.type--week,
.vxe-input--panel.type--year {
    z-index: 9998 !important;
}

/v-deep/.vxe-select--panel {
    z-index: 9997 !important;
}

/v-deep/.el-input.is-disabled .el-input__inner {
    color: #4a5261 !important;
}
</style>
